package org.telemoney;

import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class StatusServlet
 */
public class StatusServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public StatusServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("Telemoney return page(Asynchronous...)");
		System.out.println(new Date() + "invokde status url get method here....");
		
		System.out.println("-----attributes-----");
		Enumeration<String> attributes = request.getAttributeNames();
		while(attributes.hasMoreElements()){
			String key = attributes.nextElement();
			System.out.println(key + "-----" + request.getAttribute(key));
		}
		
		System.out.println("-----headers-----");
		Enumeration<String> headerNames = request.getHeaderNames();
		while(headerNames.hasMoreElements()){
			String key = headerNames.nextElement();
			System.out.println(key + "-----" + request.getHeader(key));
		}
		
		System.out.println("-----request-----");
		Map<String,String[]> map = request.getParameterMap();
		for(Map.Entry<String, String[]> entry : map.entrySet()){
			System.out.println(entry.getKey() + "----" + handelResponseValue(entry.getValue()));
		}
		
		String mid = request.getParameter("mid");
		String ref = request.getParameter("ref");
		String status = request.getParameter("status");
		
		
		String back = "mid=" + mid + "&ref=" + ref + "&ack=" + status;
		System.out.println(new Date() + "write response... " + back);
//		response.getWriter().print(back);
		response.getWriter().write(back);
//		response.getWriter().append("Served at: ").append(request.getContextPath());
	}
	
	private String handelResponseValue(String[] para){
		StringBuffer sb = new StringBuffer();
		for(int i = 0 ; i < para.length; i++){
			sb.append(para[i]).append("| ");
		}
		return sb.toString();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println(new Date() + "invokde status url post method here....");
		doGet(request, response);
	}

}
